package kz.kstu.scantest.desktop.ui.dialog;


import kz.kstu.scantest.business.client.key.KeyDigestWorker;
import kz.kstu.scantest.business.client.key.KeyXmlCreator;
import kz.kstu.scantest.business.entity.Key;
import kz.kstu.scantest.business.util.DateUtil;
import kz.kstu.scantest.business.util.FileUtil;
import kz.kstu.scantest.business.util.NumberUtil;
import kz.kstu.scantest.desktop.api.KeyFileFilter;
import kz.kstu.scantest.desktop.util.GUIUtils;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Date;

public class GenerateKeyFileDialog extends JDialog {

    private static final String TITLE = "Создание ключа";
    private static final String KEY_FLE_EXTENSION = ".crt";

    private static final int WIDTH = 320;
    private static final int HEIGHT = 280;
    private static final String KEY_FILE_SUCCESSFULLY_CREATED = "Ключ успешно создан";
    private static final String CREATE_FILE_MESSAGE = "Создания ключа";

    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField numberTextField;
    private JTextField writeOffCountTextField;
    private JTextField maxCountTextField;
    private JTextField expiredDateTextField;

    public GenerateKeyFileDialog() {
    }

    public void init() {
        initStaticComponent();
        initData();
        initListeners();
        GUIUtils.centerAndShow(this);
    }

    private void initData() {
        Date now = new Date();
        String date = DateUtil.formatDate(now, DateUtil.REG_NUMBER_DATE_PATTERN);
        //TODO: Hard code. Add reg number generator
        String regNumber = date + "01";
        numberTextField.setText(regNumber);
    }

    private void initStaticComponent() {
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        getRootPane().setDefaultButton(buttonOK);
        setContentPane(contentPane);
        setSize(WIDTH, HEIGHT);
        setTitle(TITLE);
        setResizable(false);
    }

    private void initListeners() {
        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {

        Key key = new Key();

        key.setNumber(numberTextField.getText());

        Integer countToWriteOff = NumberUtil.parseInt(writeOffCountTextField.getText());
        key.setWriteOffCount(countToWriteOff);

        Integer maxCount = NumberUtil.parseInt(maxCountTextField.getText());
        key.setMaxCount(maxCount);

        Date expiredDate = DateUtil.parseDate(expiredDateTextField.getText(), DateUtil.SIMPLE_DATE_PATTERN);
        key.setExpiryDate(expiredDate);

        KeyDigestWorker digestWorker = new KeyDigestWorker();
        digestWorker.digest(key);

        KeyXmlCreator keyXmlCreator = new KeyXmlCreator();
        String xml = keyXmlCreator.create(key);

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new KeyFileFilter());
        int state = fileChooser.showSaveDialog(this);
        if (state == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            String path = file.getAbsolutePath();
            if (!path.endsWith(KEY_FLE_EXTENSION)) {
                path += KEY_FLE_EXTENSION;
            }
            try {
                FileUtil.writeToFile(path, xml);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JOptionPane.showMessageDialog(this, KEY_FILE_SUCCESSFULLY_CREATED, CREATE_FILE_MESSAGE, JOptionPane.INFORMATION_MESSAGE);
        dispose();
    }

    private void onCancel() {
        dispose();
    }
}
